/*
 * @Author: mengxiangji
 * @Email: 397082664@qq.com
 * @Date: 2020-07-03 14:05:27
 * @Last Modified by: mxj
 * @Last Modified time: 2020-07-28 09:24:51
 * @Description: 备课小作业学生提交-查看/批阅
 */

import 'dart:typed_data';

import 'package:auto_orientation/auto_orientation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_code_framework/model_data/homeworkstudentinfo/homeworkstudentinfo.dart';
import 'package:flutter_code_framework/pages/common/image.dart';
import 'package:flutter_code_framework/route/route_transition.dart';
import 'package:flutter_code_framework/utils/global.dart';

import 'package:flutter_code_framework/widgets/voice_homework_player_widget.dart';
import 'package:flutter_code_framework/widgets/x_video_player.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';

class HomeworkReview extends BaseWidget {
  String studentHomeworkId;
  String classId;

  HomeworkReview({Key key, this.studentHomeworkId, this.classId})
      : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _HomeworkReviewState();
  }
}

class _HomeworkReviewState extends BaseWidgetState<HomeworkReview>
    with TickerProviderStateMixin {
  TabController _tabController;
  List<String> tabchilds = [];
  String nowclassId;
  String nowstudentHomeworkId;
  String audioId = "";
  String nowAudioUrl = "";
  String nowEditPicId = "";
  String evaluateResult = "";
  String evaluateRemark = "";
  HomeworkStudentInfo reviewInfo;
  double _screenHeight = 0;
  double _videoheight = 280;

  @override
  Widget buildWidget(BuildContext context) {
    _screenHeight = MediaQuery.of(context).size.height;
    Widget namewidget = Container(
      padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                  child: Row(children: <Widget>[
                Text(reviewInfo.studentName + " ",
                    style: TextStyle(
                        color:
                            Theme.of(context).primaryTextTheme.headline2.color,
                        fontSize: 28.0)),
                Icon(
                  SFSymbols.person_crop_square,
                  size: 24.0,
                  color: Theme.of(context).primaryColor,
                ),
              ]))),
          GestureDetector(
            child: Icon(
              SFSymbols.rosette,
              size: 18.0,
              color: Theme.of(context).accentColor,
            ),
            onTap: () {
              showPingJia();
            },
          ),
          GestureDetector(
            child: Container(
                child: Text(evaluateResult == "" ? "进行评价" : evaluateResult,
                    softWrap: false,
                    style: TextStyle(
                        fontWeight: FontWeight.w500,
                        color: Theme.of(context).accentColor,
                        fontSize: 18.0))),
            onTap: () {
              showPingJia();
            },
          )
        ],
      ),
    );

    Widget timewidget = Container(
        padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
        child: Column(
          children: <Widget>[
            Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.fromLTRB(0, 16, 0, 6),
                child: Text("打开时间：" + this.reviewInfo.openTime,
                    style: TextStyle(
                        fontWeight: FontWeight.w500,
                        color:
                            Theme.of(context).primaryTextTheme.headline4.color,
                        fontSize: 16.0))),
            Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.fromLTRB(0, 0, 0, 23),
                child: Text("提交时间：" + this.reviewInfo.submitTime,
                    style: TextStyle(
                        fontWeight: FontWeight.w500,
                        color:
                            Theme.of(context).primaryTextTheme.headline4.color,
                        fontSize: 16.0)))
          ],
        ));

    Widget tabnav = TabBar(
      indicatorColor: Theme.of(context).primaryColor,
      labelColor: Theme.of(context).primaryColor,
      labelStyle: TextStyle(fontSize: 18.0),
      unselectedLabelColor: Theme.of(context).primaryTextTheme.headline6.color,
      tabs: tabchilds.map((e) => Tab(text: e)).toList(),
      controller: _tabController,
    );

    Widget tabcontent = Expanded(
        child: TabBarView(
      controller: _tabController,
      children: List.generate(tabchilds.length, (index) {
        if (tabchilds[index] == "文字") {
          return SingleChildScrollView(
              padding: EdgeInsets.fromLTRB(24, 7, 24, 0),
              child: Text(
                this.reviewInfo.words,
                overflow: TextOverflow.visible,
                style: TextStyle(
                    height: 1.7,
                    fontSize: 14.0,
                    color: Theme.of(context).primaryTextTheme.caption.color),
              ));
        } else if (tabchilds[index] == "图片") {
          return ListView(
              children: List.generate(this.reviewInfo.imgList.length, (index) {
            return GestureDetector(
              child: Container(
                  padding: EdgeInsets.fromLTRB(24, 16, 24, 0),
                  alignment: Alignment.center,
                  child: Image.network(
                    this.reviewInfo.imgList[index].imgUrl,
                    alignment: Alignment.center,
                    fit: BoxFit.fitWidth,
                  )),
              onTap: () {
                editPic(this.reviewInfo.imgList[index].homeworkDetailId,
                    this.reviewInfo.imgList[index].imgUrl);
              },
            );
          }));
        } else if (tabchilds[index] == "音频") {
          return ListView(children: <Widget>[
            Container(
                padding: EdgeInsets.fromLTRB(14, 40, 14, 0),
                alignment: Alignment.center,
                child: VoiceHomeworkPlayerWidget(
                    url: nowAudioUrl, key: voicehomeworkplayer)),
            Container(
                padding: EdgeInsets.fromLTRB(24, 15, 24, 0),
                child: Row(children: <Widget>[
                  Text("学生提交的音频列表 ",
                      style: TextStyle(
                          color:
                              Theme.of(context).primaryTextTheme.caption.color,
                          fontSize: 18.0)),
                  Icon(
                    SFSymbols.music_note_list,
                    size: 16.0,
                    color: Theme.of(context).primaryColor,
                  ),
                ])),
            Padding(
              padding: EdgeInsets.fromLTRB(24, 12, 24, 14),
              child: Container(
                  alignment: Alignment.topLeft,
                  child: Wrap(
                      spacing: 6,
                      runSpacing: 6,
                      children: List.generate(this.reviewInfo.audioList.length,
                          (index) {
                        return IconButton(
                          onPressed: audioId !=
                                  this
                                      .reviewInfo
                                      .audioList[index]
                                      .homeworkDetailId
                              ? () => playaudio(
                                  this
                                      .reviewInfo
                                      .audioList[index]
                                      .homeworkDetailId,
                                  this.reviewInfo.audioList[index].audioUrl)
                              : null,
                          iconSize: 70.0,
                          icon: Icon(
                            SFSymbols.tv_music_note_fill,
                            size: 70.0,
                          ),
                          color: Theme.of(context).disabledColor,
                          disabledColor: Theme.of(context).accentColor,
                        );
                      }))),
            ),
          ]);
        } else if (tabchilds[index] == "视频") {
          return ListView(
            padding: EdgeInsets.fromLTRB(0, 0, 0, 80),
            children: List.generate(this.reviewInfo.videoList.length, (index) {
              return AnimatedContainer(
                  padding: EdgeInsets.fromLTRB(0, 6, 0, 10),
                  height: _videoheight,
                  width: double.infinity,
                  curve: Curves.easeIn,
                  duration: Duration(microseconds: 350),
                  child: XVideoPlayer(
                    isPlay: false,
                    isFullScreen: false,
                    isMaxDisplay: false,
                    path: [
                      PlayerInputInstance(title: ' ', list: [
                        VideoType(
                            name: '标清',
                            url: this.reviewInfo.videoList[index].videoUrl)
                      ])
                    ],
                    backCall: _changeFullScreen,
                  ));
            }),
          );
        }
        return Text("");
      }),
    ));

    return Container(
        padding: EdgeInsets.fromLTRB(0, 26, 0, 0),
        width: double.infinity,
        color: Colors.transparent,
        child: Stack(children: <Widget>[
          Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                namewidget,
                timewidget,
                tabnav,
                tabcontent,
              ]),
          Positioned(
            bottom: 24,
            left: 24,
            child: GestureDetector(
              child: Container(
                  color: Colors.transparent,
                  child: Icon(SFSymbols.chevron_left_circle,
                      size: 38,
                      color:
                          Theme.of(context).primaryTextTheme.headline6.color)),
              onTap: () {
                prestudent();
              },
            ),
          ),
          Positioned(
            bottom: 24,
            right: 24,
            child: GestureDetector(
              child: Container(
                color: Colors.transparent,
                child: Icon(SFSymbols.chevron_right_circle,
                    size: 38,
                    color: Theme.of(context).primaryTextTheme.headline6.color),
              ),
              onTap: () {
                nextstudent();
              },
            ),
          )
        ]));
  }

  _changeFullScreen(bool isFull) {
    // if (isFull) {
    //   setState(() {
    //     _videoheight = _screenHeight;
    //   });
    //   //全屏 强制横屏
    //   AutoOrientation.landscapeRightMode();
    //   //启动横屏陀螺仪
    //   AutoOrientation.landscapeAutoMode();
    //   setState(() {
    //     _videoheight = MediaQuery.of(context).size.width;
    //   });
    // } else {
    //   AutoOrientation.fullAutoMode();
    //   setState(() {
    //     _videoheight = 280;
    //   });
    // }
  }

  void editPic(String _picId, String _picUrl) {
    nowEditPicId = _picId;
    RouteTransition(ImageWidget(
            imageType: ImageType.edit, imageUrl: _picUrl, callback: picSave))
        .pushTransRoute(context);
  }

  GetPickImagePath picSave(ByteData bytes) {
    G.req.homeworkStudentInfoData
        .homeworkMarkingPic(
            homeworkDetailId: this.nowEditPicId, picbytedata: bytes)
        .then((rs) {
      if (rs.data['markingPicUrl'] != null) {
        showRightToast('批阅图片保存成功');
        setState(() {
          this
              .reviewInfo
              .imgList
              .firstWhere((n) => n.homeworkDetailId == this.nowEditPicId)
              .imgUrl = rs.data['markingPicUrl'].toString();
        });
        Navigator.pop(context);
      }
    });
  }

  void nextstudent() {
    if (this.reviewInfo.nextStuHomeworkId == "") {
      showWrongToast('这已是最后一个学生了');
      return;
    }
    this.nowstudentHomeworkId = this.reviewInfo.nextStuHomeworkId;
    _getReviewInfo();
  }

  void prestudent() {
    if (this.reviewInfo.preStuHomeworkId == "") {
      showWrongToast('这是第一个学生');
      return;
    }
    this.nowstudentHomeworkId = this.reviewInfo.preStuHomeworkId;
    _getReviewInfo();
  }

  void showPingJia() {
    showBottomSheetDialog(
        StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
      final evaluateRemarkcontroller = TextEditingController();
      evaluateRemarkcontroller.addListener(() {
        evaluateRemark = evaluateRemarkcontroller.text;
      });
      evaluateRemarkcontroller.text = evaluateRemark;
      return Container(
          height: 425.0,
          color: Colors.transparent,
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
            child: Column(
              children: <Widget>[
                Container(
                  child: TextField(
                    controller: evaluateRemarkcontroller,
                    maxLines: 8,
                    decoration: InputDecoration(
                        contentPadding: EdgeInsets.fromLTRB(24, 14, 24, 14),
                        fillColor: Theme.of(context).textSelectionColor,
                        filled: true,
                        hintText: "说点什么",
                        hintStyle: TextStyle(
                            color: Theme.of(context).cursorColor,
                            fontSize: 18.0),
                        border: InputBorder.none),
                  ),
                ),
                Container(
                    padding: EdgeInsets.fromLTRB(21, 0, 21, 0),
                    child: Row(
                      children: <Widget>[
                        IconButton(
                          onPressed: null,
                          iconSize: 30.0,
                          icon: Icon(
                            SFSymbols.rosette,
                            size: 30.0,
                          ),
                          color: Theme.of(context).disabledColor,
                          disabledColor: Theme.of(context).accentColor,
                        ),
                        Radio(
                          value: 'A+',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'A+',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Theme.of(context).accentColor),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "A+";
                            })
                          },
                        )),
                        Radio(
                          value: 'A',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'A',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Theme.of(context).accentColor),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "A";
                            })
                          },
                        )),
                        Radio(
                          value: 'A-',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'A-',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Theme.of(context).accentColor),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "A-";
                            })
                          },
                        )),
                      ],
                    )),
                Container(
                    padding: EdgeInsets.fromLTRB(21, 0, 21, 0),
                    child: Row(
                      children: <Widget>[
                        IconButton(
                          onPressed: null,
                          iconSize: 30.0,
                          icon: Icon(
                            SFSymbols.rosette,
                            size: 30.0,
                          ),
                          color: Theme.of(context).disabledColor,
                          disabledColor: Color.fromRGBO(184, 168, 67, 1),
                        ),
                        Radio(
                          value: 'B+',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'B+',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Color.fromRGBO(184, 168, 67, 1)),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "B+";
                            })
                          },
                        )),
                        Radio(
                          value: 'B',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'B',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Color.fromRGBO(184, 168, 67, 1)),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "B";
                            })
                          },
                        )),
                        Radio(
                          value: 'B-',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'B-',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Color.fromRGBO(184, 168, 67, 1)),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "B-";
                            })
                          },
                        )),
                      ],
                    )),
                Container(
                    padding: EdgeInsets.fromLTRB(21, 0, 21, 0),
                    child: Row(
                      children: <Widget>[
                        IconButton(
                          onPressed: null,
                          iconSize: 30.0,
                          icon: Icon(
                            SFSymbols.rosette,
                            size: 30.0,
                          ),
                          color: Theme.of(context).disabledColor,
                          disabledColor: Theme.of(context).primaryColor,
                        ),
                        Radio(
                          value: 'C+',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'C+',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Theme.of(context).primaryColor),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "C+";
                            })
                          },
                        )),
                        Radio(
                          value: 'C',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'C',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Theme.of(context).primaryColor),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "C";
                            })
                          },
                        )),
                        Radio(
                          value: 'C-',
                          groupValue: evaluateResult,
                          onChanged: (value) {
                            setState(() {
                              evaluateResult = value;
                            });
                          },
                        ),
                        Expanded(
                            child: GestureDetector(
                          child: Text(
                            'C-',
                            style: TextStyle(
                                fontSize: 18.0,
                                color: Theme.of(context).primaryColor),
                          ),
                          onTap: () => {
                            setState(() {
                              evaluateResult = "C-";
                            })
                          },
                        )),
                      ],
                    )),
                GestureDetector(
                  child: Container(
                      padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
                      color: Theme.of(context).textSelectionColor,
                      child: Text("完成",
                          softWrap: false,
                          style: TextStyle(
                              fontWeight: FontWeight.w500,
                              color: Theme.of(context).primaryColor,
                              fontSize: 18.0))),
                  onTap: () {
                    saveEvaluateResult();
                  },
                )
              ],
            ),
          ));
    }));
  }

  Future saveEvaluateResult() async {
    if (this.evaluateResult.trim() != "" || this.evaluateRemark.trim() != "") {
      G.req.homeworkStudentInfoData
          .homeworkStudentEvaluateSave(
              studentHomeworkId: this.nowstudentHomeworkId,
              evaluateInfo: this.evaluateRemark,
              evaluateResult: this.evaluateResult)
          .then((rs) {
        if (rs.data['isOk'] == true) {
          showRightToast('评价成功！');
        }
      });
    }
    Navigator.pop(context);
  }

  @override
  void initState() {
    super.initState();
    setAppTopNavBarVisible(true);
    setTopNavTitle("");
    setTopNavLeftIcon(SFSymbols.xmark);
    tabchilds.add("文字");
    _tabController = TabController(vsync: this, length: 1);
    this.reviewInfo = HomeworkStudentInfo(
        words: "",
        studentName: "",
        audioList: [],
        imgList: [],
        videoList: [],
        openTime: "",
        submitTime: "",
        evaluateInfo: "",
        evaluateResult: "",
        nextStuHomeworkId: "",
        preStuHomeworkId: "",
        reviewTime: "");
    this.nowclassId = this.widget.classId;
    this.nowstudentHomeworkId = this.widget.studentHomeworkId;
    _getReviewInfo();
  }

  //获取小作业班级学生数据
  _getReviewInfo() async {
    var reviewInfoTmp = await G.req.homeworkStudentInfoData
        .getHomeworkStudentInfo(
            studentHomeworkId: this.nowstudentHomeworkId,
            classId: this.nowclassId);
    setState(() {
      if (reviewInfoTmp.data['info'] != null) {
        this.reviewInfo =
            HomeworkStudentInfo.fromJson(reviewInfoTmp.data["info"]);
        this.evaluateResult = this.reviewInfo.evaluateResult;
        this.evaluateRemark = this.reviewInfo.evaluateInfo;
        tabchilds.clear();
        if (this.reviewInfo.words != "") {
          tabchilds.add("文字");
        }
        if (this.reviewInfo.imgList.length > 0) {
          tabchilds.add("图片");
        }
        if (this.reviewInfo.audioList.length > 0) {
          tabchilds.add("音频");
          audioId = this.reviewInfo.audioList[0].homeworkDetailId;
          nowAudioUrl = this.reviewInfo.audioList[0].audioUrl;
        }
        if (this.reviewInfo.videoList.length > 0) {
          tabchilds.add("视频");
        }
        if (tabchilds.length == 0) {
          tabchilds.add("文字");
        }
        _tabController = TabController(vsync: this, length: tabchilds.length);
      }
    });
    if (this.reviewInfo.studentName != "" && this.reviewInfo.reviewTime == "") {
      G.req.homeworkStudentInfoData.homeworkStudentReviewSave(
          studentHomeworkId: this.nowstudentHomeworkId);
    }
  }

  @override
  //自定义头部导航右侧操作区域S
  Widget getTopNavRightWidget(_contextBaseFunction) {
    return GestureDetector(
      child: Container(
          color: Colors.transparent,
          child: Text('完成',
              style: TextStyle(
                  fontSize: 14, color: Theme.of(context).primaryColor))),
      onTap: () {
        Navigator.pop(context);
      },
    );
  }

  Future<int> playaudio(String _audioId, String _audiourl) async {
    print(_audiourl);
    setState(() {
      audioId = _audioId;
      nowAudioUrl = _audiourl;
    });
    voicehomeworkplayer.currentState.setPlayerUrlPlay(_audiourl, "");
    return 1;
  }

  @override
  void onCreate() {}

  @override
  void onPause() {}

  @override
  void onResume() {}

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}
